﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using Model;
using EntityServices;
using System.Web.Http.Cors;

namespace WebApp1.Controllers
{
    [EnableCors(origins: "*", headers: "*", methods: "*")]
    public class 课程Controller : ApiController
    {
        TimeTableOneEntityServicesFactory entityServices = new TimeTableOneEntityServicesFactory();
        // GET api/<controller>

        [HttpGet]
        [Route("api/课程/课程")]
        public IEnumerable<课程> Get()
        {
            return entityServices.课程Service.GetList();
        }

        public 课程 Get(int id)
        {
            return entityServices.课程Service.GetById(id);
        }

        [HttpGet]
        [Route("api/课程/{id}/课程详情")]
        // GET api/<controller>/5
        public 课程 GetInfo(int id)
        {
            课程 result = entityServices.课程Service.GetById(id);
            result.学期 = entityServices.教师Service.GetById(result.教师Id).姓名;
            return result;
        }

        [HttpGet]
        [Route("api/课程/{id}/课程")]
        // GET api/<controller>/5
        public 课程 GetCourse(int id)
        {
            return entityServices.课程Service.GetById(id);
        }

        [HttpPost]
        [Route("api/课程/添加课程/{flag}/{uId}")]
        // POST api/<controller>
        public void Post([FromBody]课程 value, int flag, int uId)
        {
            if (value != null)
            {
                if (flag == 1)
                    entityServices.课程Service.NewSave(value);
                else
                {
                    value.班级Id = null;
                    entityServices.课程Service.NewSave(value);
                    用户 temp = entityServices.用户Service.GetById(uId);
                    temp.课程Id = value.Id;
                    entityServices.用户Service.Modify(temp);
                }

            }

        }

        [HttpPost]
        [Route("api/课程/修改课程/{flag}/{uId}")]
        public void modifyCourse([FromBody]课程 value, int flag, int uId)
        {

            Delete(value.Id);
            Post(value, flag, uId);
        }

        // PUT api/<controller>/5
        public void Put(int id, [FromBody]string value)
        {
        }

        [HttpDelete]
        [Route("api/课程/{id}")]
        // DELETE api/<controller>/5
        public void Delete(int id)
        {
            课程 temp = entityServices.课程Service.GetById(id);
            if (temp != null)
            {
                List<用户> user = entityServices.用户Service.GetList();
                foreach (用户 t in user)
                {
                    if (t.课程Id == temp.Id)
                    {
                        t.课程Id = null;
                    }
                }


                entityServices.课程Service.Remove(temp);
            }
        }


    }
}